const express = require('express');
const { v4: uuidv4 } = require('uuid');
const router = express.Router();

// 标记餐厅今天不想吃
router.post('/today', async (req, res) => {
  try {
    const { restaurantId } = req.body;
    
    if (!restaurantId) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '餐厅ID不能为空',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    // 获取餐厅信息
    const { data: restaurant, error: restaurantError } = await req.supabase
      .from('restaurants')
      .select('*')
      .eq('id', restaurantId)
      .single();
    
    if (restaurantError || !restaurant) {
      return res.status(404).json({
        success: false,
        data: null,
        message: '餐厅不存在',
        error: {
          code: 404,
          type: 'NotFound',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    // 计算过期时间（今天结束）
    const expiresAt = new Date();
    expiresAt.setHours(23, 59, 59, 999);
    
    const mark = {
      id: uuidv4(),
      restaurant_id: restaurantId,
      restaurant_name: restaurant.name,
      mark_type: 'today',
      created_at: new Date().toISOString(),
      expires_at: expiresAt.toISOString()
    };
    
    const { data, error } = await req.supabase
      .from('restaurant_marks')
      .insert([mark])
      .select()
      .single();
    
    if (error) throw error;
    
    res.json({
      success: true,
      data: data,
      message: '已标记今天不想吃'
    });
  } catch (error) {
    console.error('标记失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '标记失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 标记餐厅这周不想吃
router.post('/week', async (req, res) => {
  try {
    const { restaurantId } = req.body;
    
    if (!restaurantId) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '餐厅ID不能为空',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    // 获取餐厅信息
    const { data: restaurant, error: restaurantError } = await req.supabase
      .from('restaurants')
      .select('*')
      .eq('id', restaurantId)
      .single();
    
    if (restaurantError || !restaurant) {
      return res.status(404).json({
        success: false,
        data: null,
        message: '餐厅不存在',
        error: {
          code: 404,
          type: 'NotFound',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    // 计算过期时间（本周结束）
    const now = new Date();
    const expiresAt = new Date(now);
    const daysUntilSunday = 7 - now.getDay();
    expiresAt.setDate(now.getDate() + daysUntilSunday);
    expiresAt.setHours(23, 59, 59, 999);
    
    const mark = {
      id: uuidv4(),
      restaurant_id: restaurantId,
      restaurant_name: restaurant.name,
      mark_type: 'week',
      created_at: new Date().toISOString(),
      expires_at: expiresAt.toISOString()
    };
    
    const { data, error } = await req.supabase
      .from('restaurant_marks')
      .insert([mark])
      .select()
      .single();
    
    if (error) throw error;
    
    res.json({
      success: true,
      data: data,
      message: '已标记这周不想吃'
    });
  } catch (error) {
    console.error('标记失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '标记失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

module.exports = router;